
package hk.ces.oxfam.patch.db.result;

import hk.ces.oxfam.patch.db.sql.PreparedSQL;
import java.util.List;
import java.util.Map;

/**
 *
 * @author ReutyCheng
 */
public class BaseSQLResult implements SQLResult
{
  private final PreparedSQL preparedSQL;
  private String[] columnNames;
  private List<Object[]> rows;

  private int rowCount;
  private int columnCount;

  public BaseSQLResult(PreparedSQL preparedSQL)
  {
    this.preparedSQL = preparedSQL;
  }

  public String getSql()
  {
    return this.preparedSQL.getSql();
  }

  public Object[] getParams()
  {
    return this.preparedSQL.getParams();
  }

  public Map<String, String> getMetas()
  {
    return this.preparedSQL.getMetas();
  }

  public void setColumnNames(String[] columnNames)
  {
    this.columnNames = columnNames;
    this.columnCount = columnNames.length;
  }

  public void setRows(List<Object[]> rows)
  {
    this.rows = rows;
    this.rowCount = this.rows.size();
  }

  public String[] getColumnNames()
  {
    return columnNames;
  }

  public List<Object[]> getRows()
  {
    return rows;
  }

  public int getColumnCount()
  {
    return columnCount;
  }

  public int getRowCount()
  {
    return rowCount;
  }

  public boolean isRowsEmpty()
  {
    return rows.isEmpty();
  }

  public <T> T getColumnValue(int columnIndex, int rowIndex, Class<T> clazz)
  {
    if (columnIndex >= columnCount || rowIndex >= rowCount)
    {
      throw new IllegalArgumentException("Doesn't exist Column Index [" + columnIndex + "], Row Index [" + rowIndex + "]");
    }

    return (T) rows.get(rowIndex)[columnIndex];
  }

  public <T> T getColumnValue(String columnName, int rowIndex, Class<T> clazz)
  {
    int columnIndex = this.getColumnIndex(columnName);
    return this.getColumnValue(columnIndex, rowIndex, clazz);
  }

  public <T> T[] getColumnValues(int columnIndex, T[] array)
  {
    if (columnIndex >= columnCount)
    {
      throw new IllegalArgumentException("Doesn't exist Column Index [" + columnIndex + "]");
    }

    int row = 0;
    for (Object[] innerResult : rows)
    {
      array[row++] = (T) innerResult[columnIndex];
    }

    return array;
  }

  public <T> T[] getColumnValues(String columnName, T[] array)
  {
    int columnIndex = this.getColumnIndex(columnName);
    return this.getColumnValues(columnIndex, array);
  }

  public int getColumnIndex(String columnName)
  {
    for (int index = 0; index < columnNames.length; index++)
    {
      if (columnNames[index].equalsIgnoreCase(columnName))
      {
        return index;
      }
    }

    throw new IllegalArgumentException("Doesn't exist Column [" + columnName + "]");
  }
}
